//
//
//	simpleSlide 1.6
//
//	website:http://www.simplesli.de/
//	author: David Drew
//	email:  david@ddrewdesign.com
//	
//
//	simpleSlide is a jQuery plugin that addresses the problem of lack of designer control over
//  their slideshow plugin. The philosophy was to create a plugin that would take care of the
//	mundane issues of instantiating a slideshow plugin, but make it easy for a designer to
//	manipulate the parts of the process that they would want control over, such as visual
//	treatment, integration and additional functionality.
//
//	Parameters
//	----------
//
//	simpleSlide is instantiated, at minimum, like this:
//	
//	simpleSlide();
//
//	Upon activating this function, simpleSlide goes into your DOM and finds several key
//	elements. The simpleSlide HTML structure (and key elements) will look like this:
//
//	<div class="simpleSlide-window" rel="group_name">
//		<div class="simpleSlide-tray" rel="group_name">
//			<div class="simpleSlide-slide" rel="group_name">
//				/* Individual slide content. If content is merely an image, simpleSlide will
//				 * automatically configure each slide to accommodate the slide. If you have
//				 * opted to create content that doesn't have an apparent width or height, it
//				 * it may be in your best interest to give this content a defined width and
//				 * height. You do not, however, need to define the "simpleSlide-slide" class'
//				 * width and height. The function will take care of that for you.
//				 */
//			</div>
//		</div>
//	</div>
//
//	The user may also instantiate a graphical representative element vis-a-vis the simpleSlide
//	status element. This element is entirely optional, and will or will not be placed based on the
//	user's desire to place the following elements into their HTML:
//
//	<div class="simpleSlideStatus-tray" rel="group_name">
//		<div class="simpleSlideStatus-window" rel="group_name"></div>
//	</div>
//	
//	Please visit http://www.simplesli.de and click on "features" for more configuration information.
//
//	It should be noted, however, that after simpleSlide() has processed this structure, each slide
//  will house an "alt" attribute with an integer as its value. This integer (counting up from '1')
//	represents that slide's "page" placement among the slides in the window. This is to help the
//	designer set up functionality that allows page jumping.
//
//	The buttons that control the slideshow may be used in whatever manner you wish, and anywhere
//	in the site's structure that you wish to place them. They only must have the same "rel" as
//	the window (and accompanying elements) you wish for them to control. simpleSlide() automatically
//	treats them as clickable regions. "jump-to" is special in that you also have to pass the
//	desired "jump-to" page through the "alt" attribute.
//	
//	<div class="left-button" rel="group_name"></div>
//	<div class="right-button" rel="group_name"></div>
//  <div class="jump-to" rel="group_name" alt="1"></div>
//
//	The user is also allowed several options that they may customize. They are instantiated like this:
//	
//	simpleSlide({
//		'status_width': 20,				// Integer. Sets the width of the status slideshow's window element.
//		'status_color_inside': '#000', 	// String. Sets color of status window element.
//		'status_color_outside': '#FFF', // String. Sets color of status tray element.
//		'set_speed': 500, 				// Integer. Sets speed of all animations. Represented in milliseconds.
//		'swipe' : 'false', 				// String. 'true' turns on swipe functionality for touch devices.
//		'callback': 'function()'		// String. Sets callback to actuate after simpleSlide initial config.
//	});
//
//	If you have any further questions on the usage of simpleSlide, or suggestions on making it better,
//	please e-mail me at david@ddrewdesign.com, or visit http://www.ddrewdesign.com/contact/ to email me.
//	Thank you for using this plugin, and I hope you enjoy it. I had a blast making it.
//
// 
var iframeLoaded = false;
function simpleSlide(incoming_options) {
	
	jQuery(function($) {
		var options = {
			'set_speed': 500,
			'swipe': 'false',
            'slide_adjustment': 0,
            'landscape': 'false',
            'current' : 1,
			'callback': 'function()'
		};
		
		$.extend(options, incoming_options);
		$.ss_options = options;
		var caller = $.ss_options.functions;
		$('.simpleSlide-slide').css('opacity', '0');
		$('.simpleSlide-tray').css('margin', '0');
		$('.simpleSlide-window').prepend('<span id="ssLoading" style="color: #808080;font-family:Helvetica, Arial, sans-serif;font-size: 12px; margin: 10px 0 0 10px;display: block">Loading slides...</span>');
		var no_of_images = $('.simpleSlide-slide img').size();
			
		if(no_of_images > 0) {
			var images = new Array();
			var i = 0;
			$('.simpleSlide-slide img').each( function() {
				images[i] = $(this).attr('src');
				i++;
			});
			i = 0;
			$(images).each( function(){
				var imageObj = new Image();
				imageObj.src = images[i];
                                
				if(imageObj.complete){
					no_of_images--;
					i++;
					if(no_of_images == 0) {
						simpleSwipeAction = ssInit(caller);
					};
				} else { 
				    $(imageObj).load( function() {
				  	    no_of_images--;
					    i++;
					    if(no_of_images == 0){
					    	simpleSwipeAction = ssInit(caller);
					    };
				    });
				};
			});
		} else {
			simpleSwipeAction = ssInit(caller);
		};	
	});
};

function ssInit(caller){
	/* Set the dimensions of each simpleSlide window and tray
	 * based on the size of the first 'slide' inside that window.
	 * Every slide within a given tray/window should be uniform in dimensions.
	 * Also, set Status Window size, if it's being used. Fire callback when finished.
	 */
	jQuery(function($) {
		$('.simpleSlide-window').each( function() {	
			var window_contents = $(this).html();	
			var cleaned_contents = removeWhiteSpace(window_contents);
			$(this).html(cleaned_contents);
			var slide_count = $(this).find('.simpleSlide-slide').size();		
			$(this).find('.simpleSlide-slide').css('display','block');
			var window_height = $(this).find('.simpleSlide-slide').first().outerHeight();

			$(this).find('.simpleSlide-slide').css({
				'display':'inline',
				'float':'left'
			});
			
			var window_width = parseInt($(this).find('.simpleSlide-slide').first().outerWidth()) ;
			var window_rel = $(this).attr('rel');
            var viewport = parseInt($('.simpleSlide-window').innerWidth());
            var last_slide_adjustment = viewport - window_width;
            var margin = parseInt($(this).find('.simpleSlide-slide').css('margin-right'));
            
            $(this).css({
                'height': window_height,
              //  'width': viewport,
                'position': 'relative'
            });

            if ($.ss_options.landscape == 'true'){
                $.ss_options.slide_adjustment = window_width*2;
                $.ss_options.last_slide_adjustment = parseInt(viewport - (window_width*2));
            }else{
                $.ss_options.slide_adjustment = window_width;
                $.ss_options.last_slide_adjustment = last_slide_adjustment;
            }

			$(this).css('overflow','hidden');

			setTraySize(this, slide_count, window_width, margin);
			
			setSimpleSlideStatus(window_height, window_width, slide_count);

			$(this).find('#ssLoading').remove();
						
			if($.ss_options.swipe == 'true' && !$.browser.msie){
				simpleSwipe(this, caller);
			};
					
			$(this).find('.simpleSlide-slide').animate({
				'opacity': '1'
			}, 300, "swing");
		});
		
		/* Fire callback after completion of image load and simpleSlide initialization */
		if(typeof($.ss_options.callback) == 'function'){
			$.ss_options.callback.call(this);
		};

		/* Sets size of the "tray" that holds the "slides" */
		function setTraySize(slideWindow, count, viewer_width, margin) {
			var slider_width = (count * margin) + (viewer_width * count);
			$(slideWindow).find('.simpleSlide-tray').css({
				'width': slider_width
			});
			$(slideWindow).find('.simpleSlide-slide').css('display','inline-block');
		};	

		function setSimpleSlideStatus(height, width, image_count) {
            var landscape_status =  Math.ceil(image_count/2);
			for (var i=1; i<=image_count; i++){
                if(i==1){
                    jQuery('<div class="active jump-to" rel="secondaryPromo" alt="'+i+'"/>').appendTo('.simpleSlideStatus-tray');
                }else if(i>landscape_status){
                    jQuery('<div class="jump-to" rel="secondaryPromo" alt="'+i+'"/>',{class:'landscapeStatus'}).appendTo('.simpleSlideStatus-tray');
                }else{
                    jQuery('<div class="jump-to" rel="secondaryPromo" alt="'+i+'"/>').appendTo('.simpleSlideStatus-tray');
                }
            }
            if ($.ss_options.landscape == 'true'){
                $('.simpleSlideStatus-tray .landscapeStatus').css('display','none');
            }
		};
						
		/* Actuates upon the clicking of a left- or right-button classed element */
		$('.left-button, .right-button, .jump-to').live('click', function() {
			
			var rel = $(this).attr('rel');
			
			if (!$('div.simpleSlide-tray[rel="' + rel + '"]').is(':animated')) {
				simpleSlideAction(this, rel, caller);
			};
		});
	});
	
};

function simpleSwipe(this_window, caller) {
	var ssa;
	$(this_window).swipeleft(function(){
        ssa = simpleSlideAction('.right-button', null, caller);
        $.stopSwipeSlideShow();
    })
    $(this_window).swiperight(function(){
        ssa = simpleSlideAction('.left-button', null, caller);
        $.stopSwipeSlideShow();
    })
};

function simpleSlideOrientation(e){
    var slide_width = parseInt($('div.simpleSlide-tray').find('.simpleSlide-slide').first().outerWidth()) ;
    var viewport = $('.simpleSlide-window').outerWidth(true);
    var last_slide_adjustment = viewport - slide_width;
   // $('.simpleSlide-window').css('width',viewport)

    if (e.orientation == 'landscape'){
        $.ss_options.landscape = 'true';
        $.ss_options.slide_adjustment = slide_width*2;
        $.ss_options.last_slide_adjustment = parseInt(viewport - (slide_width*2));
        $('.simpleSlideStatus-tray .landscapeStatus').css('display','none');
    }else{
        $.ss_options.landscape = 'false';
        $.ss_options.slide_adjustment = slide_width;
        $.ss_options.last_slide_adjustment = last_slide_adjustment;
        $('.simpleSlideStatus-tray .landscapeStatus').css('display','inline-block');
    }
    $.ss_options.current = 1;
    $('.simpleSlideStatus-tray div.active').removeClass('active');
    $('.simpleSlideStatus-tray div').first().addClass('active');
    $('.simpleSlide-tray').animate({
        'marginLeft': 0
    }, $.ss_options.set_speed, "swing");
}
function simpleSlideAction(action, rel_no, caller) {
	jQuery(function($) {
        var landscape =  $.ss_options.landscape;
		var move_speed = $.ss_options.set_speed;
        var slide_adjustment = $.ss_options.slide_adjustment;
        var current_slide = $.ss_options.current;
        var last_slide_adjustment = $.ss_options.last_slide_adjustment;
		var image_count = $('.simpleSlide-window').find('.simpleSlide-slide').size();
		var status_window_width = $('.simpleSlideStatus-window[rel="' + rel_no + '"]').innerWidth();
		var margin = parseInt($(this).find('.simpleSlide-slide').css('margin-right'));
		var slideWidth = parseInt($(this).find('.simpleSlide-slide').css('width'));
		var viewport = parseInt($('.simpleSlide-window').innerWidth());
		
        if (landscape == 'true'){
             if(image_count%2 == 1){
                last_slide_adjustment += parseInt($('.simpleSlide-window').find('.simpleSlide-slide').first().outerWidth());
            }
            image_count = Math.ceil(image_count/2);
        }

		var window_width =  parseInt($(this).find('.simpleSlide-slide').first().outerWidth());
        var current_tray_margin = parseInt($('.simpleSlide-tray').css('marginLeft'), 10);

		if($(action).is('.left-button')) {
            if($.ss_options.current==2){
                var oldStatus = $('.simpleSlideStatus-tray div.active');
                var newStatus =  oldStatus.prev();
                var j_margin = 0;
                move(j_margin, oldStatus, newStatus);
                $.ss_options.current--;
            }
            /*if($.ss_options.current==image_count){
                var oldStatus = $('.simpleSlideStatus-tray div.active');
                var newStatus =  oldStatus.prev();
                //var j_margin = current_tray_margin + (window_width - last_slide_adjustment);
                var j_margin =  current_tray_margin + ((slideWidth+margin)*image_count)/image_count;
                move(j_margin, oldStatus, newStatus);
                $.ss_options.current--;
            }*/
            else if($.ss_options.current>1){
                var oldStatus = $('.simpleSlideStatus-tray div.active');
                var newStatus =  oldStatus.prev();
                //var j_margin = current_tray_margin + window_width;
                var j_margin =  current_tray_margin + ((slideWidth+margin)*image_count)/image_count;
                move(j_margin, oldStatus, newStatus);
                $.ss_options.current--;
            };
		};
		
		if($(action).is('.right-button')) {
            if($.ss_options.current==(image_count-1)){
                var oldStatus = $('.simpleSlideStatus-tray div.active');
                var newStatus =  oldStatus.next();
                //var j_margin = current_tray_margin - (window_width - last_slide_adjustment);
                var j_margin = (current_tray_margin - ((slideWidth+margin)*image_count)/image_count) + (viewport - slideWidth);
                move(j_margin, oldStatus, newStatus);
                $.ss_options.current++;
            }
            else if($.ss_options.current<(image_count -1)){
                var oldStatus = $('.simpleSlideStatus-tray div.active');
                var newStatus =  oldStatus.next();
                //var j_margin = (current_tray_margin - window_width);
                var j_margin =  current_tray_margin - ((slideWidth+margin)*image_count)/image_count;
                move(j_margin, oldStatus, newStatus);
                $.ss_options.current++;
            };
		};
		
		//adding jump-to function which will skip to a particular slide within the viewport - jjw 9/19/12
		if($(action).is('.jump-to')){
			var to_page = $(action).attr('alt');
			var j_margin = (to_page - 1) * (window_width * (-1));
			var sw_margin = (to_page - 1) * (status_window_width);
			var st_margin = (to_page - 1) * (status_window_width * (-1));
			var oldStatus = $('.simpleSlideStatus-tray div.active');
			var newStatus = $('.simpleSlideStatus-tray div[alt='+to_page+']');
			$(oldStatus).removeClass('active');
			$(newStatus).addClass('active');
			move(j_margin, sw_margin, st_margin);
		};
	
		function move(new_margin, oldStatus, newStatus) {
			$('.simpleSlide-tray').animate({
				'marginLeft': new_margin
			}, move_speed, "easeOutBack",
			function(){
				//determines if we are at end of slide (in either direction)
				
				if(getEndOfSlides(caller)){
					var endMargin = (current_tray_margin - ((slideWidth+margin)*image_count)/image_count) + (viewport - slideWidth) - ((image_count-current_slide-1)*(slideWidth+margin));
					$('.simpleSlide-tray').animate({
						'marginLeft': endMargin
					}, move_speed, "easeOutBack", function(){
						var oldStatus = $('.simpleSlideStatus-tray div.active');
						var newStatus = $('.simpleSlideStatus-tray div[alt='+image_count+']');
						//current_slide = image_count-1;
						$(oldStatus).removeClass('active');
						$(newStatus).addClass('active');
					});
					
				}
			});
			
	            $(oldStatus).removeClass('active');
	            $(newStatus).addClass('active');
		};
		
		var resetSlider = function(){
			var oldStatus = $('.simpleSlideStatus-tray div.active');
			var newStatus = $('.simpleSlideStatus-tray div[alt='+1+']');
			$(oldStatus).removeClass('active');
			$(newStatus).addClass('active');
			$.ss_options.current = 1;
			move(0, oldStatus, newStatus);
		}
		
		var getEndOfSlides = function (caller){
			
			
			if(caller.getOrientation()){
				if( $('.simpleSlide-tray div').hasClass("slide")){
					var trayWidth = parseInt($('.simpleSlide-tray').css('width')),
					leftMargin = parseInt($('.simpleSlide-tray').css('margin-left')),
					slideMargin = margin,
					viewport = viewport,
					firstSlide = $('.simpleSlide-tray div.slide:first-child').position(),
					lastSlide = $('.simpleSlide-tray div.slide:last-child').position(),
					isEnd,
					calc,
					orientationChanged = true;
					var firstSlidePos = firstSlide['left'];
					var lastSlidePos = lastSlide['left'] - (slideWidth + margin);
					
					(lastSlidePos === 0) ? isEnd = true : isEnd = false;
					
					if(firstSlidePos === 0){
						var oldStatus = $('.simpleSlideStatus-tray div.active');
						var newStatus = $('.simpleSlideStatus-tray div[alt='+1+']');
						//current_slide = image_count-1;
						
						$(oldStatus).removeClass('active');
						$(newStatus).addClass('active');
					}
				}
				/*console.log("trayWidth :", trayWidth, 
						"\nleftMargin:", leftMargin, 
						"\nslide Margin: ", slideMargin,
						//"\ncalc: ", calc, 
						"\nviewport: ", viewport, 
						"\nfirst slide position: ", firstSlidePos,
						"\nlast slide position: ", lastSlidePos,
						"\norientation: ", caller.getOrientation());*/
				
				return isEnd;
			}else{
				if( $('.simpleSlide-tray div').hasClass("slide")){
					var firstSlide = $('.simpleSlide-tray div.slide:first-child').position(),
					firstSlidePos = firstSlide['left'];
					//console.log("first slide POSITION: : : : ", firstSlidePos);
					if(firstSlidePos === 0){
						//console.log("FIRST SLIDE POS ==== 0 homey");
						var oldStatus = $('.simpleSlideStatus-tray div.active');
						var newStatus = $('.simpleSlideStatus-tray div[alt='+1+']');
						//current_slide = image_count-1;
						$(oldStatus).removeClass('active');
						$(newStatus).addClass('active');
						orientationChanged = false;
					}
				}
						
				return;
			}
		}
		
		if(action === "reset"){
			resetSlider();
			return;
		}
	
	});	
};

function removeWhiteSpace(raw) {
	var cleaned_string = raw.replace(/[\r+\n+\t+]\s\s+/g, "");
	return cleaned_string;
};

/*Photoswipe functions*/
var secondaryFade = false;
var promoObj;
var reset = false;
var secondaryDiv = ".secondarySlideshow .ps-carousel .ps-carousel-content .ps-carousel-item";

var showIndicators = function(num, target){
	for(var i=0; i<num; i++){
		if(target === "main"){
			$(".indicators:first").append("<span>");
		}else if(target="second"){
			$(".indicatorsSec:last-child").append("<span>");
		}
	}

}

var showCallToAction = function(obj, objIndex, promo){
	promoObj = promo;
	var index = objIndex;
	var indexArray = [0,1,2,0,1];
	var caption = obj.target.cache.images;
	var length = caption.length;
	
	$(secondaryDiv +" h2").remove();
	for(var i=0; i<length; i++){
		
		$(secondaryDiv + "-"+i).append("<h2>"+caption[i].caption+"</h2>").fadeIn();
	}
	if(!secondaryFade)$("#secondaryPromosContainer, .indicatorsSec span").hide().fadeIn(1000);secondaryFade=true;
	//$(".indicatorsSec span").toggle();
}

var showCallToActionOnDisplay = function(obj, index, bool, swipeLeft, orientation){
	var caption = obj.cache.images;
	var length = obj.cache.images.length;

	if(index === length-1){
		var newIndex = 0;
	}else{
		var newIndex = index + 1;
	}
	
	$(secondaryDiv + " h2").fadeOut(500).remove();
	$(secondaryDiv+":nth-child(1)").append("<h2>"+caption[index-1].caption+"</h2>");
	$(secondaryDiv+":nth-child(2)").append("<h2>"+caption[index].caption+"</h2>");
	$(secondaryDiv+":nth-child(3)").append("<h2>"+caption[newIndex].caption+"</h2>");
	
	if(index > 1 && index !=length-1 && bool && swipeLeft){
		$(secondaryDiv+":nth-child(3)").hide().fadeIn(800);
	}
	
	if(index > 0 && index != length-2 && !swipeLeft){
		$(secondaryDiv+":nth-child(1)").hide().fadeIn(800);
	}
}

var showPrimaryPromo = function(){
	$("#mainPromoContainer").hide().fadeIn(1000);
}

var getImageCaption = function(){
	return $(".secondarySlideshow .ps-caption-content").text();
}

var openURL = function(obj){
	var index = obj.target.currentIndex;
	var url = obj.target.cache.images[index].metaData['href'];
	window.open(url);
}

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
    if (event.origin !== "http://view.atdmt.com" && event.origin !== "https://view.atdmt.com"){
	//console.log("you don't belong here");
    return;
}
  // ...
	
	//console.log("received message: ", event.data);
	//console.log("received from: ", event.origin);
	//event.source.postMessage("Let's trigger a click event", event.origin);
}

$(document).ready(function(){ 
	
	var length = $(".swipe div.swipe-slide").length,
		count = 1,
		swipe,
		slideShowSpeed = 3000,
		isLandscape,
		self =this,
		functions = {},
		simpleSwipeAction;
	
	$(window).bind('resize', function(event){
		checkOrientation();
	});
	
	$(window).bind('orientationchange', function(event){
		checkOrientation();
		//reset our orientation
		simpleSlideAction("reset", null, functions);
	});
	
	var showSwipeSlideShow = function(){
			window.mySwipe = new Swipe(document.getElementById('mainPromoContainer'), {
		    startSlide: 0,
		    speed: 400,
		    auto: 0, //initially stopped until loaded
		    disableScroll: true,
		    continuous: true,
		    callback: function(index, elem) {
	        // set our indicators
	    	setCurrentIndicator(index, elem);
		    }
		});

		setIndicators(length);
		
		//hide our promo container while we are loading
		$('#mainPromoContainer').css("opacity","0");
		
		//show our spinner
		 $("#primaryHeader").spin("#000000");
	}
	
	var setCurrentIndicator = function(index, elem){
		var i = index + 1;
		$(elem).parent().parent().find(".indicators span").removeClass("current");
		$(elem).parent().parent().find(".indicators span:nth-child("+i+")").addClass("current");
		$(".swipe .indicators").trigger("spgCurrentSlideChange", index);
	}
	
	var setIndicators = function(num){
		for(var i = 0; i<num; i++){
			$(".swipe .indicators").append("<span>");
		}
		$(".swipe .indicators span:first-child").addClass("current");
		$(".swipe .indicators").trigger("spgCurrentSlideChange", 0);
	}
	
	$.stopSwipeSlideShow = function(){
		if($(".swipe")[0]){
			window.mySwipe.autoStop();
		}
	}
	
	$.startSwipeSlideShow = function(val){
		if($(".swipe")[0]){
			window.mySwipe.autoStart(val);
		}
	}

	//start our primary slideshow
	showSwipeSlideShow();
	
	$(".promoIframe").load(function (){
		//console.log("our iframe is loaded");
		
		if(count === length){
			 // hide our spinner
			$("#primaryHeader .spinner").fadeOut(500).remove();
			$('#mainPromoContainer').animate({opacity: 1}, 1000);
			iframeLoaded = true;
			//start our slideshow
			$.startSwipeSlideShow(slideShowSpeed);
		}
		count++;
	});
	
	$(".iframe").click(function(e){
		var target = e.currentTarget.id.toString().split("");
		var index = target[6];
		var frame = eval("promo" + index);
		frame.postMessage("click", window.location.protocol+"//view.atdmt.com");
	})
	
	/*var iframe = $(".promoIframe").contents();
	
	if(iframe.length === 0){
		//iframes already loaded, so lets display them
		$("#primaryHeader .spinner").fadeOut(500).remove();
		$('#mainPromoContainer').animate({opacity: 1}, 1000);
	}*/
	
	var checkOrientation = function() {
	    if(window.innerHeight > window.innerWidth){
	    	isLandscape = false;
	    }else{
	    	isLandscape = true;
	    }
	};
	
	functions.getOrientation = function() {
		return isLandscape;
	};
	
	functions.setSimpleSlideAction = function(slideActionObject){
		simpleSwipeAction = slideActionObject;
	}
	
	functions.getSimpleSlideAction = function(){
		return simpleSwipeAction;
	}

     var mySimpleSlide = simpleSlide({
        'swipe': 'true',
        //commenting out for testing on desktop
        //'landscape': (screen.width>screen.height ? 'true' : 'false'),
        'set_speed' : 600,
        functions: functions
    });
     
	checkOrientation();
	functions.getOrientation();
});